using System;
using System.Collections.Generic;

namespace FrameWork
{
    public partial class ObjectPoolModule : BaseModule
    {
        private Dictionary<Type, ObjectPoolBase> _pools;

        //用来获取东西才会用到，只是缓存而已
        private List<ObjectPoolBase> _poolList;

        /// <summary>
        /// 对象池数量
        /// </summary>
        public int PoolCount
        {
            get { return _pools.Count; }
        }

        public override void Init()
        {
            _pools = new Dictionary<Type, ObjectPoolBase>();
            _poolList = new List<ObjectPoolBase>();
        }

        public override void ShutDown()
        {
            foreach (var pair in _pools)
                pair.Value.Shutdown();

            _pools.Clear();
            _poolList.Clear();
        }

        public override void Update(float deltaTime, float realDeltaTime)
        {
            foreach (var pair in _pools)
            {
                pair.Value.Update(deltaTime, realDeltaTime);
            }
        }

        /// <summary>
        /// 是否存在某个对象池
        /// </summary>
        /// <typeparam name="T">对象池类型</typeparam>
        public bool HasObjectPool<T>() where T : ObjectBase
        {
            return _pools.ContainsKey(typeof(T));
        }

        public T GetObjectPool<T>() where T : ObjectBase
        {
            Type t = typeof(T);
            if (_pools.ContainsKey(t))
            {
                return _pools[t] as T;
            }

            return null;
        }

        public ObjectPool<T> CreatePool<T>(string name) where T : ObjectBase
        {
            return CreateObjectPool<T>(name, true, float.MaxValue, int.MaxValue, float.MaxValue);
        }

        private ObjectPool<T> CreateObjectPool<T>(string name, bool allowMul, float autoReleaseInterval,
            int capacity, float expireTime) where T : ObjectBase
        {
            if (HasObjectPool<T>())
                throw new Exception("已经包含该名称的Pool了");

            ObjectPool<T> objectPool = new ObjectPool<T>(name, allowMul, autoReleaseInterval, capacity, expireTime);
            _pools.Add(typeof(T), objectPool);
            return objectPool;
        }
    }
}

